package com.geek.javase.ch16.work.work1;

/*
 *@author wangpeng
 *2025/11/2
 *@description TODO
 */

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierTest {
    public static void main(String[] args) {
        // 创建CyclicBarrier，需要2个线程到达屏障点
        CyclicBarrier barrier = new CyclicBarrier(2, () -> {
            // 当两个线程都到达屏障后执行的回调
            System.out.println("C");
        });

        // 线程1 - 打印A，然后等待屏障
        Thread thread1 = new Thread(() -> {
            System.out.println("A");
            try {
                // 等待线程2到达屏障
                barrier.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        });

        // 线程2 - 打印B，然后到达屏障
        Thread thread2 = new Thread(() -> {
            try {
                Thread.sleep(100); // 确保线程1先打印A
                System.out.println("B");
                // 到达屏障，触发回调
                barrier.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        });

        thread1.start();
        thread2.start();
    }
}